//
//  WJ_Search_ViewController.m
//  WJBSApp
//
//  Created by dllo on 16/7/14.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJ_Search_ViewController.h"
#import "WJLastModel.h"
#import "WJSearchCell.h"
#import "WJLastViewController.h"
#import "WJLastCell.h"


@interface WJ_Search_ViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain) UISearchBar *searchBar;

@property (nonatomic,retain) NSMutableArray *searchArray;

@property (nonatomic,retain) WJBaseTableView *searchTableView;

@property (nonatomic,retain) WJBaseTableView *upLable;

@property (nonatomic,retain) NSString *lableText;

@property (nonatomic,retain) MBProgressHUD *hub;

@property (nonatomic,assign) NSInteger nextPage;

@end

@implementation WJ_Search_ViewController

static NSString *const SearchCell = @"searchcell";



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.searchArray = [NSMutableArray array];
    
    self.nextPage = 1;
    
    [self createconfig];
    
    [self createView];
    
    [self p_addFooter];
}


- (void)createconfig
{
    // 影藏系统的返回按钮
    self.navigationItem.hidesBackButton = YES;
    
    // 左面的按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationButtonReturn.png" hightImage:@"navigationButtonReturnClick.png" target:self action:@selector(tjLeftAction)];
}

- (void)tjLeftAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createView
{
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, WIDTH - 100, 44)];
    self.searchBar.placeholder = @"搜索您想要关注的";
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
    
    self.upLable = [[WJBaseTableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 20) style:UITableViewStylePlain];
    [self.view addSubview:self.upLable];
    self.upLable.delegate = self;
    self.upLable.dataSource = self;
    self.upLable.rowHeight = 20;
    self.upLable.bounces = NO;
    self.upLable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.upLable registerClass:[WJLastCell class] forCellReuseIdentifier:@"upLableCell"];
    
    self.searchTableView = [[WJBaseTableView alloc]initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT - 64 - 20) style:UITableViewStylePlain];
    [self.view addSubview:self.searchTableView];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.rowHeight = HEIGHT / 9;
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.searchTableView registerClass:[WJSearchCell class] forCellReuseIdentifier:SearchCell];
    
    
    self.hub = [[MBProgressHUD alloc]init];
    [self.view addSubview:self.hub];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.searchTableView]) {
        return self.searchArray.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.searchTableView]) {
        WJSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchCell];
        WJLastModel *model = self.searchArray[indexPath.row];
        cell.model = model;
        
        
        //设置标签文字属性
        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:model.username];
        NSRange rang = [model.username rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch];
        [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:BSRedColor, NSForegroundColorAttributeName, nil] range:rang];
        cell.nameLable.attributedText = attributeString;
        
        return cell;
    }
    WJLastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"upLableCell"];
    cell.lable.text = self.lableText;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.searchTableView]) {
    WJLastViewController *last = [[WJLastViewController alloc]init];
    WJLastModel *model = self.searchArray[indexPath.row];
        last.userID = model.id;
        last.userName = model.username;
        
    [self.navigationController pushViewController:last animated:YES];
    }
}






// 显示搜索按钮 并且设置它的状态
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    attr[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    attr[NSForegroundColorAttributeName] = BSRedColor;
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"搜索"];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitleTextAttributes:attr forState:UIControlStateNormal];
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

#pragma mark -  点击搜索按钮 实现的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    // 防止出现空数据
    if (searchBar.text.length != 0) {
        
        [self.hub show:YES];

        if (self.searchArray.count != 0) {
            self.searchArray = @[].mutableCopy; //这个更完美
            self.lableText = @"";
        }
        
        [searchBar resignFirstResponder];
        NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&uname=%@&a=search&appname=baisibudejie&c=user&os=4.2.2&page=1",searchBar.text];
        
        [WJNetTool GET:url body:nil header:nil response:WJJSON success:^(id resuposeObject) {
            
            NSDictionary *dic = resuposeObject;
            NSArray *array = dic[@"list"];
            self.lableText = [NSString stringWithFormat:@"搜索结果:%@",dic[@"total"]];
            
            for (NSDictionary *dic in array) {
                WJLastModel *model = [[WJLastModel alloc]initWithDic:dic];
                [self.searchArray addObject:model];
            }
            [self.hub hide:YES];
            [self.searchTableView reloadData];
            [self.upLable reloadData];
            
            
        } failure:^(NSError *error) {}];
        
        
    }
}


#pragma mark - 实现键盘上Search按钮的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (searchBar.text.length !=0 ) {
        
        if (self.searchArray.count != 0) {
            self.searchArray = @[].mutableCopy; //这个更完美
            self.lableText = @"";
        }
        [searchBar resignFirstResponder];
        NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&uname=%@&a=search&appname=baisibudejie&c=user&os=4.2.2&page=1",searchBar.text];
        
        [WJNetTool GET:url body:nil header:nil response:WJJSON success:^(id resuposeObject) {
            
            NSDictionary *dic = resuposeObject;
            NSArray *array = dic[@"list"];
            self.lableText =[NSString stringWithFormat:@"搜索结果:%@",dic[@"total"]];
            
            for (NSDictionary *dic in array) {
                WJLastModel *model = [[WJLastModel alloc]initWithDic:dic];
                [self.searchArray addObject:model];
            }
            [self.hub hide:YES];
            [self.searchTableView reloadData];
            [self.upLable reloadData];
            
        } failure:^(NSError *error) {}];
    }
}

#pragma mark - 文本改变时的方法  完美 目的是删除数据为空时 返回第一个页面
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchText.length == 0){
        self.searchArray = @[].mutableCopy; //这个完美
        self.lableText = @"";
        [self.searchTableView reloadData];
        [self.upLable reloadData];
    }
}


#pragma mark - 上啦加载
- (void)p_addFooter
{
    self.searchTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.nextPage = self.nextPage + 1;
        NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&uname=%@&a=search&appname=baisibudejie&c=user&os=4.2.2&page=%ld",self.searchBar.text,(long)self.nextPage];
        
        [WJNetTool GET:url body:nil header:nil response:WJJSON success:^(id resuposeObject) {
            
            NSDictionary *dic = resuposeObject;
            NSArray *array = dic[@"list"];
            self.lableText = [NSString stringWithFormat:@"搜索结果:%@",dic[@"total"]];
            
            for (NSDictionary *dic in array) {
                WJLastModel *model = [[WJLastModel alloc]initWithDic:dic];
                [self.searchArray addObject:model];
            }
            [self.hub hide:YES];
            [self.searchTableView reloadData];
            [self.upLable reloadData];
            
            
        } failure:^(NSError *error) {}];
        
        
        
    }];
}










- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
